package memorytrace.requestmanagers

class RequestBackTraces(callers:java.util.ArrayList[memorytrace.domaine.StackCall],allocs:java.util.ArrayList[memorytrace.domaine.AllocEvent]) {
  
  
  private var funtionList:scala.collection.mutable.ListBuffer[String]=null
  
  /**
   * Retourne le tuple (malloc_count,calloc_count,realloc_count,free_count) de function
   */
  def selectAllocEventsWhereSourceIs(function : String):(Int,Int,Int,Int) ={
    val function_events=allocs
    
    /**
     * calcul des fragments de stack possédant la fonction function
     */
    var function_stacks = new java.util.ArrayList[Int]
    var it=callers.iterator()
    while(it.hasNext()){
      
      var x :memorytrace.domaine.StackCall = it.next()
      
      if(x.parent_func==function || x.pparent_func==function){
        function_stacks.add(x.id)
      }
    }
    
    //a ce stade function_stacks contient les stacktrace de la fonction function
    //on parcourt la liste des evenements d'allocation
    //chaque evenement possèdant un id qui est dans function_stacks est rajouté dans le resultat
    var (malloc_count,calloc_count,realloc_count,free_count)=(0,0,0,0)
    var it2=allocs.iterator()
    
    while(it2.hasNext()){
      
      var x :memorytrace.domaine.AllocEvent = it2.next()
      
		  if(function_stacks.contains(x.Id)){
			  x.EventType match{
			    case 'm' => malloc_count=malloc_count+1
			    case 'c' => calloc_count=calloc_count+1
			    case 'r' => realloc_count=realloc_count+1
			    case 'f' => free_count = free_count+1
			    case _   => 
			  }
		   }
    }
    
    (malloc_count,calloc_count,realloc_count,free_count)
  }
  
  //Retourne la liste des fonctions enregistrées par l'instrumentation
  def selectFunctionsFromBackTraces():scala.collection.mutable.ListBuffer[String]={
    if(this.funtionList!=null){
      this.funtionList
    }
    else{
    	this.funtionList = new scala.collection.mutable.ListBuffer[String]()
    			var it = callers.iterator(); 
    			while(it.hasNext()){
    			  
    			    
    			    var current:memorytrace.domaine.StackCall=null
    			    try{
    			    current=it.next()
    			    }catch{
    			      
    			      case ex:java.util.NoSuchElementException => Thread.sleep(1000) ; return this.funtionList
    			    }
    			    
	    			    if(!this.funtionList.contains(current.parent_func))
	    			    {
	    			      
	    			        //println("found: "+current.parent_func)
	    			    	//envoyer le message à l'acteur de stdin ici
	    			    	this.funtionList+=current.parent_func;
	    			    	
	    			    }
	    			    if(!this.funtionList.contains(current.pparent_func))
	    			    {
	    			        //println("found: "+current.pparent_func)
	    			    	//envoyer le message à l'acteur de stdin ici
	    			    	this.funtionList+=current.pparent_func;
	    			    }
	    			    
    			}
    	return this.funtionList
    }
  }
  
}